﻿
using System.Runtime.InteropServices;
using FFmpeg.AutoGen.Abstractions;
using FFmpeg.AutoGen.Bindings.DynamicallyLoaded;
using System;
using System.Diagnostics;
using ymk_camera_surveillance.Config;

namespace ymk_camera_surveillance.Decode;

public class FFmpegBinariesHelper
{
    internal static void RegisterFFmpegBinaries()
    {
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            //var appDataDirectory = FileSystem.Current.AppDataDirectory;
            //var envs = Environment.GetEnvironmentVariables();
            //var current = Environment.CurrentDirectory;

            var appRootPath = AppDomain.CurrentDomain.BaseDirectory;
            var probe = Path.Combine("lib");

            while (appRootPath != null)
            {
                Conf.Instance.FFmpegPath = Path.Combine(appRootPath, probe);

                if (Directory.Exists(Conf.Instance.FFmpegPath))
                {
                    Console.WriteLine($"FFmpeg binaries found in: {Conf.Instance.FFmpegPath}");
                    DynamicallyLoadedBindings.LibrariesPath = Conf.Instance.FFmpegPath;
                    DynamicallyLoadedBindings.Initialize();
                    Conf.Instance.FFmpegVersion = ffmpeg.av_version_info();
                    Debug.WriteLine($"FFmpeg version info: {Conf.Instance.FFmpegVersion}");
                    return;
                }

                appRootPath = Directory.GetParent(appRootPath)?.FullName;
            }
        }
        else
            throw new NotSupportedException(); // fell free add support for platform of your choose
    }
}
